package one.stand.controller.index;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.ArticleApi;
import com.jmp.base.TemplateApi;
import com.jmp.base.UserApi;
import com.jmp.base.dto.*;
import com.jmp.feign.TemplateFeign;
import com.jmp.feign.UserFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.*;
import one.stand.mapper.ArticleApiCrmAppMapper;
import one.stand.mapper.ArticleMapperExt;
import one.stand.model.*;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.sys.ArticleTypeService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.sys.UserContentService;
import one.stand.service.user.UserAdminService;
import one.stand.service.user.UserAdminServiceImpl;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "首页-头条")
@RestController
@RequestMapping("lead")
public class LeadController {
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private ArticleMapperExt articleMapperExt;

    @Autowired
    private ArticleApiCrmAppMapper articleApiCrmAppMapper;

    @ApiOperation(value = "1头条首页：置顶、轮播、海报")
    @PostMapping("")
    public ResultModel<LeadResponse> top() {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        final Integer companyId = requestContext.isCard() ? requestContext.getUser().getCompanyId() : ArticleApi.DEFAULT_COMPANYID;

        if (requestContext.isLogin()) {
            userFeign.viewSave(UserViewSaveDto.builder().userId(requestContext.getUser().getUserId()).type(UserApi.VIEW_TYPE_LEAD).build());
        }

        String excludeLabelIds = null;
        if (requestContext.isLogin() && !requestContext.isCard()) {
            Integer supplierLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_SUPPLIER);
            Integer jxsLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_JXS);
            excludeLabelIds = SqlUtil.in(Lists.newArrayList(String.valueOf(supplierLabelId), String.valueOf(jxsLabelId)));
        }

        //置顶
        PageHelper.startPage(1, 3);
        List<Article> articleList = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null, excludeLabelIds, null, null);
        List<LeadResponse.Top> articles = ConvertUtils.list(articleList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadResponse.Top.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .top("置顶")
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        //轮播
        PageHelper.startPage(1, 5);
        List<Article> bannerList = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_BANNER, null, excludeLabelIds, null, null);
        List<LeadResponse.Banner> banners = ConvertUtils.list(bannerList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadResponse.Banner.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .pic(article.getShareCard())
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        //海报
        List<LeadResponse.Card> cards = null;
        if (requestContext.isCard()) {
            TemplateListDto templateListDto = TemplateListDto.builder().companyId(companyId).cardId(requestContext.getUser().getCardId()).build();
            templateListDto.setPageInit(1, 3);
            ResultModel<TemplateListVo> templateListVoResultModel = templateFeign.list(templateListDto);
            if (templateListVoResultModel.isSuccess()) {
                cards = ConvertUtils.list(templateListVoResultModel.getData().getCardPage().getList(), template -> {
                    return LeadResponse.Card.builder()
                            .pic(template.getCardUrl())
                            .build();
                });
            }
        }

        LeadResponse response = LeadResponse.builder()
                .tops(articles)
                .banners(banners)
                .cards(cards)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2头条首页：首页列表（分页）")
    @PostMapping("index")
    public ResultModel<LeadIndexResponse> index(@RequestAttribute PageRequest request) {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        final Integer companyId = requestContext.isCard() ? requestContext.getUser().getCompanyId() : ArticleApi.DEFAULT_COMPANYID;

        String excludeLabelIds = null;
        if (requestContext.isLogin() && !requestContext.isCard()) {
            Integer supplierLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_SUPPLIER);
            Integer jxsLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_JXS);
            excludeLabelIds = SqlUtil.in(Lists.newArrayList(String.valueOf(supplierLabelId), String.valueOf(jxsLabelId)));
        }

        PageHelper.startPage(1, 3);
        List<Article> tops = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null, excludeLabelIds, null, null);
        PageHelper.startPage(1, 5);
        tops.addAll(articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_BANNER, null, excludeLabelIds, null, null));
        List<Integer> idsExclude = ConvertUtils.list(tops, Article::getId);
        String excludeIds = SqlUtil.in(idsExclude);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Article> articleList = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, null, excludeIds, excludeLabelIds, null, null);
        PageResponse2<LeadIndexResponse.Index> articles = ConvertUtils.page2(articleList, article -> {
            ArticleType type = articleTypeService.get(article.getTypeId());
            return LeadIndexResponse.Index.builder()
                    .id(article.getId())
                    .title(article.getTitle())
                    .type(type.getName())
                    .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                    .build();
        });

        LeadIndexResponse response = LeadIndexResponse.builder()
                .indexs(articles)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3详情")
    @PostMapping("detail")
    public ResultModel<LeadDetailResponse> detail(@RequestAttribute LeadDetailRequest request) {
        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        AssertUtil.nonNull(article, ResultEnum.PARAM_CHECK, "文章不存在");
        AssertUtil.isTrue(ArticleApi.STATUS_UP == article.getStatus(), ResultEnum.PARAM_CHECK, "文章已下架");

        LeadDetailResponse response = LeadDetailResponse.builder()
                .img(UserAdminServiceImpl.DEFAULT_IMG)
                .name("访客")
                .position(StringUtils.EMPTY)
                .companyName(StringUtils.EMPTY)

                .title(article.getTitle())
                .subTitle(article.getSubtitle())
                .origin(article.getOriginName())
                .time(DateUtil.format(DateUtil.YYYYMMDD, article.getUpTime()))
                .content(article.getContent())
                .adContent(article.getAdContent())
                .originUrl(article.getOriginUrl())

                .build();

        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        if (requestContext.isLogin()) {//登录时
            UserDto user = userAdminService.get(requestContext.getUser().getUserId());
            response.setImg(user.getUserImg());
            response.setName(user.getName());
            if (requestContext.isCard()) {//存在名片
                Company2Dto company = companyBaseService.get2(requestContext.getUser().getCompanyId());
                BusinessCard cardModel = businessCardBaseService.getCustomer(requestContext.getUser().getCardId());
                response.setPosition(cardModel.getPosition());
                response.setCompanyName(company.getCompanyName());
            }
        }

        return ResultModel.success(response);
    }

    @ApiOperation(value = "3详情：分享")
    @PostMapping("detail/share")
    @SecurityAuthCheck
    public ResultModel<LeadDetailShareResponse> detailShare(@RequestAttribute LeadDetailRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        AssertUtil.nonNull(article, ResultEnum.PARAM_CHECK, "文章不存在");
        AssertUtil.isTrue(ArticleApi.STATUS_UP == article.getStatus(), ResultEnum.PARAM_CHECK, "文章已下架");

        BusinessCard cardModel = businessCardBaseService.getCustomer(optUser.getCardId());

        if (Objects.isNull(request.getHasName())) {
            request.setHasName(1);
        }
        if (Objects.isNull(request.getHasTel())) {
            request.setHasTel(1);
        }
        if (Objects.isNull(request.getHasWxcode())) {
            request.setHasWxcode(0);
        }
        String h5Url = getH5Url(article.getId(), Objects.nonNull(cardModel) ? cardModel.getCardId() : null, BooleanUtils.toBoolean(request.getHasName()),
                BooleanUtils.toBoolean(request.getHasTel()), BooleanUtils.toBoolean(request.getHasWxcode()), optUser.getUserId());

        LeadDetailShareResponse response = LeadDetailShareResponse.builder()
                .shareTitle(article.getTitle())
                .shareSubTitle(article.getSubtitle())
                .shareImg(article.getShareCard() + "?x-oss-process=image/resize,w_100")
                .shareUrl(h5Url)
                .hasWxcode(Objects.nonNull(cardModel) && StringUtils.isNoneBlank(cardModel.getWxCode()))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3详情：分享海报")
    @PostMapping("bill")
    @SecurityAuthCheck
    public ResultModel<LeadBillResponse> bill(@RequestAttribute LeadBillRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        String h5Url = getH5Url(request.getArticleId(), optUser.getCardId(), request.isHasName(), request.isHasTel(), request.isHasWxcode(), optUser.getUserId());

        Article article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
        TemplateApi.Type type = TemplateApi.Type.valueOf("ID_CRM_APP_ARTICLE_" + article.getTemplateType());//根据选择

        TemplateGet2Request getRequest = TemplateGet2Request.builder()
                .templateType(type)
                .cardId(optUser.getCardId())
                .articleId(request.getArticleId())
                .articleH5Url(h5Url)
//                .configExclude(configExclude)
                .build();
        ResultModel<TemplateGetResponse> templateGetResponseResultModel = templateFeign.get2(getRequest);
        AssertUtil.isTrue(templateGetResponseResultModel);
        LeadBillResponse response = LeadBillResponse.builder()
                .bill(templateGetResponseResultModel.getData().getImageUrl())
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation(value = "3详情：分享成功后，添加至动态")
    @PostMapping("dynamic")
    @SecurityAuthCheck
    public ResultModel dynamic(@RequestAttribute LeadDynamicRequest request) {
//        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

//        ArticleWithBLOBs article = articleMapperExt.selectByPrimaryKey(request.getArticleId());
//        DynamicSaveRequest saveRequest = DynamicSaveRequest.builder()
//                .companyId(optUser.getCompanyId())
//                .createUserId(optUser.getUserId())
//                .type(DynamicApi.TYPE_ARTICLE)
//                .title(article.getTitle())
//                .details(article.getContent())
//                .photos(article.getShareCard())
//                .relateType(DynamicApi.RELATE_ID_ARTICLE)
//                .relateId(request.getArticleId())
//                .build();
//        dynamicFeign.save(saveRequest);

        return ResultModel.success();
    }

    @ApiOperation(value = "3详情：分享成功统计")
    @PostMapping("forward")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel forward(@RequestAttribute LeadBillRequest request) {

        articleMapperExt.updateForward(request.getArticleId());

        return ResultModel.success();
    }

    private String getH5Url(Integer articleId, Integer cardId, Boolean hasName, Boolean hasTel, Boolean hasWxcode, Integer userId) {
        DictDto articleH5Dict = sysDictValueService.get2(SysDictValueService.Type.CONFIG, SysDictValueService.TypeNameConfig.article_h5.name());
        String h5Url = String.format(articleH5Dict.getValue(), articleId, cardId);
        if (Objects.nonNull(hasName)) {
            h5Url = h5Url + "&name=" + hasName;
        }
        if (Objects.nonNull(hasTel)) {
            h5Url = h5Url + "&mobile=" + hasTel;
        }
        if (Objects.nonNull(hasWxcode)) {
            h5Url = h5Url + "&wxcode=" + hasWxcode;
        }
        h5Url = h5Url + "&userId=" + userId;
        return h5Url;
    }
}
